$(document).ready(function(){
	try{
		document.createElement("canvas").getContext("2d");
	}catch(e){
		loadJS("module/artDialog/artDialog.min.js", function(){
			art.dialog({
				title: 'Warning',
				lock: true,
				opacity: 0.15,
				content: document.getElementById('dialog')
			});
			$('.aui_close').remove();
		});
		return;
	}
	//上传
	loadJS("module/uploadify/jquery.uploadify-3.1.min.js", function(){
		$("#uploadify").uploadify({
			'uploader': 'upload',
			'swf': 'module/uploadify/uploadify.swf',
			'queueID': 'fileQueue',
			'auto': true,
			'multi': false,
			'removeCompleted': true,
			'simUploadLimit': 1,
			'sizeLimit': '5242880', // 单个文件限制  5MB(1048576)，单位byte
			'queueSizeLimit': 3,
			'fileTypeDesc': '支持格式：*.jpg; *.png',
			'fileTypeExts': '*.jpg; *.png',
			'buttonText': '浏览照片',
			'cancelImage': 'module/uploadify/uploadify-cancel.png',
			'onUploadError': function(file, errorCode, errorMsg, errorString){
				alert("文件：" + file.name + " 上传失败");
			},
			'onUploadSuccess': function(file, data, response){
				$('<img src="' + data + '" id="sourceImg" />').appendTo('#cropDiv');
				$('#uploadDiv').fadeOut(800);
				setTimeout(function(){
					$('#cropDiv').fadeIn(800);
					$('.step1').addClass('otherStep');
					$('.step2').addClass('currentStep');
					loadJS("module/jcrop/js/jquery.Jcrop.min.js", function(){
						$('#sourceImg').Jcrop({
							onChange: showCoords,
							onSelect: showCoords
						});
					});
				}, 800);
				function showCoords(c){
					$('#x').val(c.x);
					$('#y').val(c.y);
					$('#w').val(c.w);
					$('#h').val(c.h);
				};
			}
		});
	});
	//裁剪
	$('#cropBtn').click(function(){
		if($('#w').val() != 0 && $('#h').val() != 0){
			$.ajax({
				url: 'cropImg?img=' + $('#sourceImg').attr('src') + '&x=' + parseInt($('#x').val()) + '&y=' + parseInt($('#y').val()) + '&w=' + parseInt($('#w').val()) + '&h=' + parseInt($('#h').val()),
				success: function(data){
					$('#sourceImg').remove();
					$('#cropDiv').css('margin', '20px').html('<img src="' + data + '" id="sourceImg" style="display: none;" />');
					$('#sourceImg').load(function(){
						$(this).css({
							'position': 'absolute',
							'top': '100px',
							'left': ($(window).width() - $(this).width()) / 2
						}).fadeIn(300);
						setTimeout(function(){
							setWord();
						}, 2000);
					});
				}
			});
		}
	});
	$('#nextStep').click(function(){
		setWord();
	});
	// 设置关键字
	function setWord(){
		$('.step2').addClass('otherStep');
		$('.step3').addClass('currentStep');
		$('#cropDiv').fadeOut(800);
		setTimeout(function(){
			$('#setWordDiv').fadeIn(800);
			$('#word').focus();
		}, 800);
	}
	//下载
	$('#confirmBtn').click(function(){
		toDownload();
	});
	$("body").keydown(function(event){
		if(event.keyCode == 13){
			toDownload();
		}
	});
	function toDownload(){
		if($('#word').val().trim() == ''){
			return;
		}
		$('#loading').css({
			'position': 'absolute',
			'top': ($(window).height() - $('#loading')[0].clientHeight) / 2,
			'left': ($(window).width() - $('#loading')[0].clientWidth) / 2
		}).show();
		$('.step3').addClass('otherStep');
		$('.step4').addClass('currentStep');
		$('#setWordDiv').hide();
		$('#showResultImg').fadeIn(800);
		$.ajax({
			url: 'scaleImage?img=' + $('#sourceImg').attr('src'),
			success: function(data){
				// alert(data);
				$('#loading').hide();
				var canvas = document.getElementById("canvas");
				var ctx = canvas.getContext("2d");
				pWidth = 18;
				width = 0;
				height = 0;
				rgb = {};
				data = data.indexOf("error") > 0 ? eval("(" + data + ")") : data;
				if(data.error){
					alert(data.error);
					return;
				}
				if(data.length == 0){
					alert("Can't Read Image RGB Info!");
					return;
				}
				var json = eval("(" + data + ")");
				pixels = json;
				if(!isNaN(json.height)){
					width = json.width * pWidth;
					height = json.height * pWidth;
					canvas.width = width;
					canvas.height = height;
					ctx.fillStyle = 'rgba(255,255,255,1.0)';
					ctx.fillRect(0, 0, width, height);
					rgb = json.rgb;
					drawImage(rgb, json.width);
				}
				function drawImage(rgb, width){
					var rowCount = 0;
					ctx.font = "700 19px SimHei";
					for( var i = 0; i < rgb.length; i++){
						var p = rgb[i];
						ctx.fillStyle = 'rgba(' + p.red + ',' + p.green + ',' + p.blue + ',1.0)';
						var colCount = i % width;
						if(i % width == 0 && i != 0){
							rowCount++;
						}
						ctx.fillText($('#word').val(), colCount * pWidth, rowCount * pWidth, pWidth);
					}
					ctx.restore();
				}
				$('#resultImg').attr('src', canvas.toDataURL()).css({
					'position': 'absolute',
					'top': '150px',
					'left': ($(window).width() - $('#resultImg').width()) / 2,
					'zIndex': 999
				}).fadeIn(100);
				/** window.location.href = canvas.toDataURL("image/png"); */
				canvas.toBlob(function(blob){
					saveAs(blob, 'word.png');
				});
			}
		});
	}
});

/** **************** 按需加载 begin *********************************** */
function loadJS(file, callback){
	var js = document.createElement('script');
	js.setAttribute('type', 'text/javascript');
	js.setAttribute('src', file);
	document.getElementsByTagName('head')[0].appendChild(js);
	if(document.all && window.external){
		js.onreadystatechange = function(){
			if(js.readyState == 'loaded' || js.readyState == 'complete'){
				callback();
			}
		};
	}else{
		js.onload = function(){
			callback();
		};
	}
	return false;
}
/** ************** 按需加载 end **************************************** */

/*! @source http://purl.eligrey.com/github/canvas-toBlob.js/blob/master/canvas-toBlob.js */
(function(a){"use strict";var b=a.Uint8Array,c=a.HTMLCanvasElement,d=/\s*;\s*base64\s*(?:;|$)/i,f,e=function(n){var o=n.length,k=new b(o/4*3|0),m=0,q=0,r=[0,0],g=0,p=0,l,h,j;while(o--){h=n.charCodeAt(m++);l=f[h-43];if(l!==255&&l!==j){r[1]=r[0];r[0]=h;p=(p<<6)|l;g++;if(g===4){k[q++]=p>>>16;if(r[1]!==61){k[q++]=p>>>8}if(r[0]!==61){k[q++]=p}g=0}}}return k.buffer};if(b){f=new b([62,-1,-1,-1,63,52,53,54,55,56,57,58,59,60,61,-1,-1,-1,0,-1,-1,-1,0,1,2,3,4,5,6,7,8,9,10,11,12,13,14,15,16,17,18,19,20,21,22,23,24,25,-1,-1,-1,-1,-1,-1,26,27,28,29,30,31,32,33,34,35,36,37,38,39,40,41,42,43,44,45,46,47,48,49,50,51])}if(c&&!c.prototype.toBlob){c.prototype.toBlob=function(p,m){if(!m){m="image/png"}var l=Array.prototype.slice.call(arguments,1),h=this.toDataURL.apply(this,l),n=h.indexOf(","),i=h.substring(n+1),o=d.test(h.substring(0,n)),j=a.BlobBuilder||a.WebKitBlobBuilder||a.MozBlobBuilder,k=new j,g;if(j.fake){g=k.getBlob(m);if(o){g.encoding="base64"}else{g.encoding="URI"}g.data=i;g.size=i.length}else{if(b){if(o){k.append(e(i))}else{k.append(decodeURIComponent(i))}g=k.getBlob(m)}}p(g)}}}(self));

/*! @source http://purl.eligrey.com/github/FileSaver.js/blob/master/FileSaver.js */
var saveAs = saveAs||(function(h){"use strict";var r=h.document,l=function(){return h.URL||h.webkitURL||h},e=h.URL||h.webkitURL||h,n=r.createElementNS("http://www.w3.org/1999/xhtml","a"),g="download" in n,j=function(t){var s=r.createEvent("MouseEvents");s.initMouseEvent("click",true,false,h,0,0,0,0,0,false,false,false,false,0,null);return t.dispatchEvent(s)},o=h.webkitRequestFileSystem,p=h.requestFileSystem||o||h.mozRequestFileSystem,m=function(s){(h.setImmediate||h.setTimeout)(function(){throw s},0)},c="application/octet-stream",k=0,b=[],i=function(){var t=b.length;while(t--){var s=b[t];if(typeof s==="string"){e.revokeObjectURL(s)}else{s.remove()}}b.length=0},q=function(t,s,w){s=[].concat(s);var v=s.length;while(v--){var x=t["on"+s[v]];if(typeof x==="function"){try{x.call(t,w||t)}catch(u){m(u)}}}},f=function(t,u){var v=this,B=t.type,E=false,x,w,s=function(){var F=l().createObjectURL(t);b.push(F);return F},A=function(){q(v,"writestart progress write writeend".split(" "))},D=function(){if(E||!x){x=s(t)}w.location.href=x;v.readyState=v.DONE;A()},z=function(F){return function(){if(v.readyState!==v.DONE){return F.apply(this,arguments)}}},y={create:true,exclusive:false},C;v.readyState=v.INIT;if(!u){u="download"}if(g){x=s(t);n.href=x;n.download=u;if(j(n)){v.readyState=v.DONE;A();return}}if(h.chrome&&B&&B!==c){C=t.slice||t.webkitSlice;t=C.call(t,0,t.size,c);E=true}if(o&&u!=="download"){u+=".download"}if(B===c||o){w=h}else{w=h.open()}if(!p){D();return}k+=t.size;p(h.TEMPORARY,k,z(function(F){F.root.getDirectory("saved",y,z(function(G){var H=function(){G.getFile(u,y,z(function(I){I.createWriter(z(function(J){J.onwriteend=function(K){w.location.href=I.toURL();b.push(I);v.readyState=v.DONE;q(v,"writeend",K)};J.onerror=function(){var K=J.error;if(K.code!==K.ABORT_ERR){D()}};"writestart progress write abort".split(" ").forEach(function(K){J["on"+K]=v["on"+K]});J.write(t);v.abort=function(){J.abort();v.readyState=v.DONE};v.readyState=v.WRITING}),D)}),D)};G.getFile(u,{create:false},z(function(I){I.remove();H()}),z(function(I){if(I.code===I.NOT_FOUND_ERR){H()}else{D()}}))}),D)}),D)},d=f.prototype,a=function(s,t){return new f(s,t)};d.abort=function(){var s=this;s.readyState=s.DONE;q(s,"abort")};d.readyState=d.INIT=0;d.WRITING=1;d.DONE=2;d.error=d.onwritestart=d.onprogress=d.onwrite=d.onabort=d.onerror=d.onwriteend=null;h.addEventListener("unload",i,false);return a}(self));